package com.edu.demo.login.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.edu.demo.login.model.UserDomain;
import com.edu.demo.login.service.LoginService;
import com.edu.demo.login.service.SessionProvider;
import com.edu.demo.login.utlis.RequestUtils;
import com.edu.demo.login.utlis.Result;

@Controller
@RequestMapping(value = "/user")
public class LoginAction {

	@Autowired
	private LoginService loginService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private SessionProvider sessionProvider;
	
	
	@ResponseBody
	@PostMapping("/login")
	public Result<UserDomain> addUser(UserDomain user, HttpServletRequest request, HttpServletResponse response) {
	
		Result result = new Result();
		//用户名不能为空
		if (user.getUserName() == null)
		{			
			result.setCode(500);
			result.setMessage("用户名不能为空");
			return result;
		}
		//密码不能为空
		if (user.getPasswd() == null)
		{			
			result.setCode(500);
			result.setMessage("密码不能为空");
			return result;
		}
		
		UserDomain userDomain = loginService.login(user, request, response);
		if ( userDomain == null)
		{
			result.setCode(500);
			result.setMessage("用户名或密码不正确");
			return result;
			
		}
		else
		{
			String CSESSION = RequestUtils.getCSESSIONID(request, response);
			
			sessionProvider.setAttribuerForUsername(CSESSION, userDomain.getUserName());
			
			/*String ooo = sessionProvider.getAttributeForUsername(CSESSION);
			
	        System.out.println(ooo);*/
						
		}		
		result.setCode(200);
		result.setData(userDomain);
		return result;

	}
	
	@Bean
	public RedisTemplate redisTemplateInit() {
		// 设置序列化Key的实例化对象
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		// 设置序列化Value的实例化对象
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		return redisTemplate;
	}
}
